﻿
/* 
 * Since 2008 - 2012
 */
package com.hh.bss.customer.controller;

import static com.hh.bss.util.extjs.JsonHelper.outJson;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJacksonJsonView;


import com.hh.bss.base.*;
import com.hh.bss.common.page.*;
import com.hh.bss.config.Environment;
import com.hh.bss.customer.entity.*;
import com.hh.bss.customer.service.*;
import com.hh.bss.customer.vo.query.*;
import com.hh.bss.util.*;
import com.hh.bss.util.extjs.ExtJsPageHelper;
import com.hh.bss.util.extjs.JsonHelper;
import com.hh.bss.util.extjs.ListRange;

import java.util.*;





@Controller
public class CompanyNewsAttachmentController extends BaseSpringController{
	//默认多列排序,example: username desc,createTime asc
	protected static final String DEFAULT_SORT_COLUMNS = null; 
	
	private CompanyNewsAttachmentService companyNewsAttachmentService;
	
	private CompanyNewsAttachment companyNewsAttachment;
	java.lang.Integer id = null;
	private String[] items;

	
	
	/** 通过spring自动注入 */
	public void setCompanyNewsAttachmentServiceImpl(CompanyNewsAttachmentService service) {
		this.companyNewsAttachmentService = service;
	}	
	
	
	
	public void setId(java.lang.Integer val) {
		this.id = val;
	}

	public void setItems(String[] items) {
		this.items = items;
	}



	/**
	 * ExtGrid使用
	 * 列表
	 * @throws IOException
	 */
	public void list(HttpServletRequest request,HttpServletResponse response,CompanyNewsAttachmentQuery companyNewsAttachmentQuery) throws IOException
	{
		PageRequest<Map> pr = ExtJsPageHelper.createPageRequestForExtJs(request, DEFAULT_SORT_COLUMNS);
		Page page = companyNewsAttachmentService.findPage(companyNewsAttachmentQuery);
		
		List<CompanyNewsAttachment> CompanyNewsAttachmentlist = (List) page.getResult();
		ListRange<CompanyNewsAttachment> resultList = new ListRange<CompanyNewsAttachment>();
		resultList.setRows(CompanyNewsAttachmentlist);
		resultList.setTotal(page.getTotalCount());
		resultList.setMessage("ok");
		resultList.setSuccess(true);
		outJson(response,resultList);
	}

	/**
	 * extGrid保存
	 * @throws IOException
	 */
	public ModelAndView extsave(HttpServletRequest request,HttpServletResponse response,CompanyNewsAttachment companyNewsAttachment) throws IOException
	{
		MappingJacksonJsonView view = new MappingJacksonJsonView();
		Map<String, Object> responseMap = new HashMap<String, Object>();
		try
		{
                        //设置创建用户和创建时间
			com.hh.bss.auth.client.OnlineManager onlineManager=super.getOnlineManager(request, response);
			if (onlineManager!=null){
					com.hh.bss.auth.client.OnlineUser onlineUser=onlineManager.getOnlineUser();
					if (onlineUser!=null&&com.hh.bss.util.BeanUtils.isExistsProperty(CompanyNewsAttachment.class,"creator")) {
						try{com.hh.bss.util.BeanUtils.setProperty(companyNewsAttachment,"creator",onlineUser.getUsername());}catch(Exception ex){}
					}
				}
							
			if (com.hh.bss.util.BeanUtils.isExistsProperty(CompanyNewsAttachment.class,"createDt")) {
					try{com.hh.bss.util.BeanUtils.setProperty(companyNewsAttachment,"createDt",new Date());}catch(Exception ex){}
				}

			MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
			MultipartFile multipartFile = multipartHttpServletRequest.getFile("uploadFile");
			String originalFileName = multipartFile.getOriginalFilename();
			SimpleDateFormat dateformat = new SimpleDateFormat("yyyy/MM/dd/HH");
			String logoPathDir = "/uploadNewAttach/";
		    String logoRealPathDir =  request.getSession().getServletContext().getRealPath(logoPathDir);
            Long size = multipartFile.getSize();
            String fileType = StringUtils.substring(originalFileName,StringUtils.lastIndexOf(".", originalFileName)+1);
            Integer fileSize = size.intValue();
			File file = new File(logoRealPathDir);
			if(!file.exists()){
				file.mkdir();
			}
			try {
				System.out.println(file.getAbsolutePath());
				FileOutputStream fileOutputStream = new FileOutputStream(file+ "/"+originalFileName);
				fileOutputStream.write(multipartFile.getBytes());
				fileOutputStream.flush();
				fileOutputStream.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
				responseMap.put("success", false);
				responseMap.put("msg", e.getMessage());
			} catch (IOException e) {
				e.printStackTrace();
				responseMap.put("success", false);
				responseMap.put("msg", e.getMessage());
			}
			companyNewsAttachment.setAttachmentFile(logoPathDir+originalFileName);
			companyNewsAttachment.setAttachmentName(originalFileName);
			companyNewsAttachment.setAttachmentFilesize(fileSize);
			companyNewsAttachment.setAttachmentFiletype(fileType);

		    //***上传文件处理结束****
		  String new_id=request.getParameter("new_id");
		  if(new_id != null ||!"".equals(new_id)){
			  companyNewsAttachment.setNewsId(Integer.valueOf(StringHelper.parseInteger(new_id, 0)));
		   }
		
		   companyNewsAttachmentService.save(companyNewsAttachment);
		   responseMap.put("success", true);
		   responseMap.put("msg", "添加成功!");
		}
		catch (Exception e)
		{
			responseMap.put("failure", true);
			responseMap.put("msg", e.getMessage());
			e.printStackTrace();
		}
		 view.setContentType("text/html");
		 response.setContentType("text/html");
		 responseMap.put("success", true);
		 responseMap.put("msg", "上传成功");
		 ModelAndView mav = new ModelAndView(view, responseMap);
		 return mav;
	}
	public void filesave(HttpServletRequest request,HttpServletResponse response,CompanyNewsAttachment companyNewsAttachment) throws IOException
	{
		
		    MultipartHttpServletRequest multipartRequest=null;
		       try{
		    	   multipartRequest = (MultipartHttpServletRequest) request;
		       }catch(Exception ex){}
		        
		       //multipart/form-data 提交模式，则处理上传文件
		       if (multipartRequest!=null){
		    	   System.out.println("处理上传文件");
			       SimpleDateFormat dateformat = new SimpleDateFormat("yyyyMMdd");     
			       /**构建文件保存的web目录**/     
			       String fileWebPathDir = Environment.UPLOADFILEDIR+"/"+CompanyNewsAttachment.FILETYPE+dateformat.format(new Date());      
			       /**得到文件保存目录的真实路径**/     
			       String fileRealPathDir = request.getSession().getServletContext().getRealPath(fileWebPathDir);     
			       /**根据真实路径创建目录**/     
			       File fileSaveDir = new File(fileRealPathDir);     
			       if(!fileSaveDir.exists()) {    
			           fileSaveDir.mkdirs();     
			       }   
			       /**页面控件的文件流**/     
			       MultipartFile multipartFile = multipartRequest.getFile("fileRes");      
			       
			       //文件不为空，处理上传文件
			       if (multipartFile!=null){
					       /**上传文件名称**/     
					       String uploadFileName = multipartFile.getOriginalFilename();//    
					         
					          
					       /**获取文件的后缀**/     
					       String suffix = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf(".")+1);     
					       // 文件类型   
					         
					       // 获取文件大小，以kB为单位   
					       long size = multipartFile.getSize();   
					       Double fSize =Math.round(size/1024.0*100)/100.0;   
					       String fileSize = Double.toString(fSize)+"KB";     
					       /**拼成完整的文件保存路径加文件**/     
					       String fileName = fileRealPathDir + File.separator   + uploadFileName;     
			
					       File file = new File(fileName);      
					          
					       try {     
					           multipartFile.transferTo(file);  //将文件写入到指定的目录   
					       } catch (IllegalStateException e) {     
					           e.printStackTrace();     
					       } catch (IOException e) {            
					           e.printStackTrace();     
					       }    
					       companyNewsAttachment.setAttachmentFile(fileWebPathDir+"/"+ uploadFileName);
					       companyNewsAttachment.setAttachmentFilesize(fSize.intValue());
					       companyNewsAttachment.setAttachmentFiletype(suffix);
			       }
		       }
		       //companyNewsAttachment.getAttachmentName()
		   companyNewsAttachmentService.save(companyNewsAttachment);
		   
		   JsonHelper.outString(response, "hello"); 
		
	}
	
	/**
	 * extGrid修改
	 * @throws IOException
	 */
	public void update(HttpServletRequest request,HttpServletResponse response,CompanyNewsAttachment companyNewsAttachment) throws IOException
	{
		Map<String, Object> result = new HashMap<String, Object>();
		try
		{
                        CompanyNewsAttachment oldcompanyNewsAttachment = (CompanyNewsAttachment)companyNewsAttachmentService.getById(companyNewsAttachment.getId());
                         
			bind(request,oldcompanyNewsAttachment);
                        //设置修改用户和修改时间 
                        com.hh.bss.auth.client.OnlineManager onlineManager=super.getOnlineManager(request, response);
			if (onlineManager!=null){
					com.hh.bss.auth.client.OnlineUser onlineUser=onlineManager.getOnlineUser();
					if (onlineUser!=null&&com.hh.bss.util.BeanUtils.isExistsProperty(CompanyNewsAttachment.class,"modifier")) {
						try{com.hh.bss.util.BeanUtils.setProperty(oldcompanyNewsAttachment,"modifier",onlineUser.getUsername());}catch(Exception ex){}
					}
				}
							
			if (com.hh.bss.util.BeanUtils.isExistsProperty(CompanyNewsAttachment.class,"modifiedDt")) {
					try{com.hh.bss.util.BeanUtils.setProperty(oldcompanyNewsAttachment,"modifiedDt",new Date());}catch(Exception ex){}
				}


			companyNewsAttachmentService.update(oldcompanyNewsAttachment);
			result.put("success", true);
			result.put("msg", "修改成功!");
		}
		catch (Exception e)
		{
			result.put("failure", true);
			result.put("msg", e.getMessage());
			e.printStackTrace();
		}
		outJson(response,result);
	}
	
	/**
	 * extGrid删除
	 * @throws IOException
	 */
	public void delete(HttpServletRequest request,HttpServletResponse response) throws IOException
	{
		String ids = request.getParameter("ids");
		String[] idarray = ids.split(",");
		Map<String, Object> result = new HashMap<String, Object>();
		try
		{
			for (int i = 0; i < idarray.length; i++)
			{
				java.lang.Integer id = new java.lang.Integer((String)idarray[i]);
				companyNewsAttachmentService.removeById(id);
			}
			result.put("success", true);
			result.put("msg", "删除成功");
		}
		catch (Exception e)
		{
			result.put("failure", true);
			result.put("msg", e.getMessage());
			e.printStackTrace();
		}
		outJson(response,result);
	}
	
}
